# models.py
import os
import time
from datetime import datetime
from django.db import models


# 自定义的上传路径和文件名函数
def user_avatar_upload_to(instance, filename):
    # 获取当前日期
    today = datetime.today()
    # 根据日期生成目录：年/月/日
    directory = today.strftime('%Y/%m/%d')

    # 获取当前的时间戳
    timestamp = int(time.time())

    # 文件扩展名保持不变
    extension = os.path.splitext(filename)[1]

    # 构建新的文件名: 时间戳.扩展名
    new_filename = f"{timestamp}{extension}"

    # 返回文件的完整路径：年月日目录/时间戳.扩展名
    return os.path.join(directory, new_filename)


# User 模型
class User(models.Model):
    username = models.CharField(max_length=150, unique=True)
    nickname = models.CharField(max_length=30, blank=True)
    password = models.CharField(max_length=128)  # 密码应该加密存储
    email = models.EmailField(unique=True, blank=True, null=True)
    phone_number = models.CharField(max_length=15, blank=True, null=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)  # 是否是管理员
    date_joined = models.DateTimeField(auto_now_add=True)


    # 使用自定义上传路径函数，设置默认头像
    user_avatar = models.ImageField(
        upload_to=user_avatar_upload_to,
        blank=True,
        null=True,
        default='defaults/default_avatar.jpg'  # 默认头像路径
    )

    def __str__(self):
        return self.username

    def set_password(self, raw_password):
        """加密密码并存储"""
        from django.contrib.auth.hashers import make_password
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        """验证密码"""
        from django.contrib.auth.hashers import check_password
        return check_password(raw_password, self.password)
